package com.mark.common.utils;

import com.mark.common.enums.PropertiesEnum;
import com.mark.common.utils.PathUtil;
import com.mark.web.data.exception.FileUtilException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Description: 文件转换的工具类
 * @Author: Kingsley
 * @CreateDate: 2018/10/28 19:04
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Slf4j
public class FileUtil {
    private static final String SEPARATOR  = System.getProperty(PropertiesEnum.FILE_SEPARATOR.getPropertiesName());
    private static final String BASE_PATH = PathUtil.getImageBasePath();

    /**
     * File -> MultipartFile(图片的装换)
     * @param targetFile :待转换的file文件
     * @return ：转换成MultipartFile格式的文件
     */
    public static MultipartFile fileToMultipartFile(File targetFile){
        return fileToMultipartFile(targetFile, "image/jpeg");
    }

    public static MultipartFile fileToMultipartFile(File targetFile,String contentType){
        if (targetFile == null) {
            throw new FileUtilException("输入的File文件不能为空！");
        }
        FileInputStream inputStream = null;
        MultipartFile multipartFile = null;
        try {
            inputStream = new FileInputStream(targetFile);
            multipartFile = new MockMultipartFile(targetFile.getName(),targetFile.getName(),contentType, inputStream);
        } catch (IOException e) {
            log.error("[file To MultipartFile Exception：]"+e.getMessage());
            throw new FileUtilException("file -> MultipartFile 异常");
        }
        return multipartFile;
    }

    /**
     * MultipartFile-> FileSystemResource
     * @param multipartFile :待转换的原始文件MultipartFile
     * @return ： 转换后FileSystemResource格式的文件
     */
    public static FileSystemResource multipartFileToFileSystemResource(MultipartFile multipartFile){
        FileSystemResource result;
        //1.校验
        if (multipartFile == null) {
            throw new FileUtilException("输入的MultipartFile文件不能为空！");
        }
        String originalFileFileName = multipartFile.getOriginalFilename();
        if(StringUtils.isNotBlank(originalFileFileName)){
            throw new FileUtilException("输入的MultipartFile文件的原始文件名不能为空！");
        }

        //2.检查存储文件的base路径是否存在，不存在则新建
        String localBasePath = BASE_PATH;
        try {
            File file = new File(localBasePath);
            //如果localBasePath路径不存在，则建立该路径
            if (!file.exists()) {
                boolean writable = file.setWritable(true);
                boolean mkdirsRes = file.mkdirs();
                if(!writable || !mkdirsRes ){
                    log.info("自动生成目标文件路径"+localBasePath+"失败");
                }
            }
        }catch (Exception e){
            throw new FileUtilException("生成目标文件路径:" + localBasePath + "异常" + e.getMessage());
        }

        //3.新建本地文件
        String localFilePath = localBasePath + SEPARATOR + originalFileFileName;
        File localFile = new File(localFilePath);

        //4.将MultipartFile写到本地文件中
        try {
            multipartFile.transferTo(localFile);

            //5.本地文件装换为 FileSystemResource
            result = new FileSystemResource(localFile);
        } catch (IOException e) {
            throw new FileUtilException("MultipartFile文件装换为File文件异常："+e.getMessage());
        }
        return result;
    }
}
